package com.ics.cmsadmin.modules.pub.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.pub.bean.Course;
import com.ics.cmsadmin.modules.pub.bean.Order;
import com.ics.cmsadmin.modules.pub.service.impl.CourseServiceImpl;
import com.ics.cmsadmin.modules.pub.service.OrderService;
import com.ics.cmsadmin.modules.sso.utils.SsoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/courses")
public class CoursesController extends ResourceController<CourseServiceImpl, Course, Integer> {

    @Resource(name = "CourseService")
    private CourseServiceImpl courseServiceImpl;

    @Autowired
    private OrderService orderService;

    @GetMapping
    public ApiResponse coursesGet(String name, Integer subjectId, Boolean isActive, Integer teacherId, Integer courseTypeId,
                                  @RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  HttpServletRequest request) {
        String userId = SsoUtils.getLoginUserId(request);
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("subjectId", subjectId);
        param.put("isActive", isActive);
        param.put("teacherId", teacherId);
        param.put("courseTypeId", courseTypeId);
        param.put("page", page);
        param.put("pageSize", pageSize);
        if (page != null && pageSize != null) {
            PageHelper.startPage(page, pageSize);
        } else {
            List<Course> data = courseServiceImpl.getMultiple(param, userId);
            long total = data.size();
            return ApiResponse.getDefaultResponse(PageResult.getPage(total, data));
        }
        List<Course> data = courseServiceImpl.getMultiple(param, userId);
        long total = ((Page) data).getTotal();
        PageResult pageResult = PageResult.getPage(total, data);
        return ApiResponse.getDefaultResponse(pageResult);
    }

    /**
     * 获取用户已购买课程
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/purchased")
    public ApiResponse userCourse(@RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  HttpServletRequest request) {
        String userId = SsoUtils.getLoginUserId(request);
        PageResult pageResult = new PageResult();
        // 未登陆
        if (StringUtils.isEmpty(userId)) {
            pageResult.setDataList(new ArrayList<Course>());
            return ApiResponse.getDefaultResponse(pageResult);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("status", 2); // 已购买
        List<Order> orderList = orderService.list(params, page, pageSize);
        List<Integer> courseIds = orderList.stream().map(Order::getProductId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(courseIds)) {
            pageResult.setDataList(new ArrayList<Course>());
            return ApiResponse.getDefaultResponse(pageResult);
        }
        List<Course> courseList = courseServiceImpl.findByIdIn(courseIds, userId);
        long total = ((Page) orderList).getTotal();
        pageResult.setTotalCount(total);
        pageResult.setDataList(courseList);
        return ApiResponse.getDefaultResponse(pageResult);
    }



    @PutMapping("/{id}/courseType/{courseTypeId}")
    public ApiResponse courseCourseTypePut(@PathVariable Integer id, @PathVariable Integer courseTypeId) {
        int result = courseServiceImpl.setCourseType(id, courseTypeId);
        if (result != 0) {
            return ApiResponse.getDefaultResponse();
        } else {
            return ApiResponse.getResponse(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL);
        }
    }

    @DeleteMapping("/{id}/courseType/{courseTypeId}")
    public ApiResponse courseCourseTypeDelete(@PathVariable Integer id, @PathVariable Integer courseTypeId) {
        int result = courseServiceImpl.unsetCourseType(id, courseTypeId);
        if (result != 0) {
            return ApiResponse.getDefaultResponse();
        } else {
            return ApiResponse.getResponse(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL);
        }
    }

    @DeleteMapping("/courseType/{courseTypeId}")
    public ApiResponse courseCourseTypeDeleteMultiple(@PathVariable Integer courseTypeId, @RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            int effectLine = courseServiceImpl.unsetCourseType(id, courseTypeId);
            if (effectLine == 0) {
                throw new CmsException(ApiResultEnum.BULK_UPDATE_FAIL);
            }
        }
        return ApiResponse.getDefaultResponse();
    }

    @GetMapping("/{courseId}/detail")
    public ApiResponse get(@PathVariable Integer courseId,
                           HttpServletRequest request) {
        String userId = SsoUtils.getLoginUserId(request);
        return ApiResponse.getDefaultResponse(courseServiceImpl.get(courseId, userId));
    }

    /**
     * 记录课程点击量
     *
     * @param id
     * @return
     */
    @GetMapping("/view/{id}")
    public ApiResponse increaseViewNum(@PathVariable Integer id) {
        courseServiceImpl.increaseViewNum(id);
        return ApiResponse.getDefaultResponse();
    }
}
